package com.menusifu.cloudmenu.dao.impl;

import com.menusifu.cloudmenu.dao.TaxDao;
import com.menusifu.cloudmenu.entity.Tax;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xie
 * @date 2019/1/15 14:13
 * @description:
 */
@Repository
public class TaxDaoImpl implements TaxDao {
    @Autowired
    MongoTemplate mongoTemplate;
    
    @Override
    public List<Tax> getAllTaxes() {
        Query query = new Query(Criteria.where("deleted").is(Boolean.FALSE));
        return mongoTemplate.find(query, Tax.class);
    }

    @Override
    public Tax addTax(Tax tax) {
        return mongoTemplate.insert(tax, "Tax");
    }

    @Override
    public void updateTax(Tax tax) {
        Query query = new Query(Criteria.where("id").is(tax.getId()).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("name", tax.getName())
                .set("description", tax.getDescription())
                .set("rate", tax.getRate())
                .set("lastUpdated", tax.getLastUpdated());
        mongoTemplate.findAndModify(query, update, Tax.class);
    }

    @Override
    public void deleteTax(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("deleted", Boolean.TRUE);
        mongoTemplate.findAndModify(query, update, Tax.class);
    }

    @Override
    public Tax getTaxById(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        return mongoTemplate.findOne(query, Tax.class);
    }
}
